package net.zjitc.service.Impl;

import com.google.gson.Gson;
import java.sql.SQLException;
import java.util.List;
import net.zjitc.dao.AdminDao;
import net.zjitc.dao.OrderDao;
import net.zjitc.dao.ProductDao;
import net.zjitc.dao.UserCartDao;
import net.zjitc.pojo.CartItem;
import net.zjitc.pojo.Order;
import net.zjitc.pojo.Orderitem;
import net.zjitc.pojo.Product;
import net.zjitc.pojo.User;
import net.zjitc.redis.Redis;
import net.zjitc.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/5/17 14:25
 * @description:
 */
@Service
public class OrderServiceImpl implements OrderService{
  @Autowired
  OrderDao orderDao;
  @Autowired
  private UserCartDao userCartDao;
  @Autowired
  private Redis redis;
  @Autowired
  private ProductDao productDao;
  @Override
  public List<Order> findByUid(Integer uid) {
    List<Order> orders=orderDao.findByUid(uid);
    for (Order o:orders){
      //通过订单号找到对应的订单项
      List<Orderitem> orderitemList=orderDao.findOrderitemByOid(o.getOid());
      //通过pid找到订单项对应的的产品
      for (Orderitem orderitem:orderitemList){
        //通过Iitemid找到订单项对应的的pid
        Integer spid=orderDao.findPidByItemid(orderitem.getItemid());
        Integer pid=Integer.valueOf(spid);
        Product product=productDao.findByPid(pid);
        //设置订单项的产品
        orderitem.setProduct(product);
      }
      o.setOrderitemList(orderitemList);
    }
    return orders;
  }

  @Override
  public int add(Order order, List<Orderitem> orderitemList) {
    int count1=orderDao.add(order);
    System.out.println(orderitemList);
    for (Orderitem o : orderitemList){
      int count2=orderDao.orderitem(o);
    }

    userCartDao.clearCart(order.getUid());
    Gson gson =new Gson();
    List<CartItem> cartItems =userCartDao.findAll();
    String cartlist = gson.toJson(cartItems);
    redis.set("cartitem",cartlist);
    return count1;
  }

  @Override
  public List<Order> findAll() {
    return orderDao.findAll();
  }

  @Override
  public List<Orderitem> findOrderitemByOid(String oid) {
    return orderDao.findOrderitemByOid(oid);
  }

  @Override
  public Integer editPayState(Order order) {
    return orderDao.editState(order);
  }

  @Override
  public Integer editOsatate(Orderitem orderitem) {
    return orderDao.editOsatate(orderitem);
  }

  @Override
  public Integer editOstateByItemid(Integer itemid) {
    return orderDao.editOstateByItemid(itemid);
  }


}
